import axios from 'axios'
import { ElMessage } from 'element-plus';
import router from '@/router'

const contentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8";
const contentTypeJson = "application/json";
const contentTypeFile = "multipart/form-data";

const request = (config) => {
  let { url, params, dataType = 'form', showLoading = 'true' } = config
  let contentType = contentTypeForm
  if (dataType === 'json') {
    contentType = contentTypeJson
  } else if (dataType === 'file') {
    contentType = contentTypeFile
    let param = new FormData()
    for (let key in params) {
      param.append(key, params[key])
    }
    params = param
  }

  const instance = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
      'Content-Type': contentType,
      'X-Requested-With': 'XMLHttpRequest'
    }
  })

  //请求前拦截
  instance.interceptors.request.use((config) => {
    return config
  }, (error) => {
    ElMessage({
      message: '出错了!',
      type: 'error',
    })
    return Promise.reject("发送请求失败!")
  })

  // 请求后拦截
  instance.interceptors.response.use((response) => {
    const responseData = response.data
    if (responseData.status == "error") {
      if (config.errorCallback) {
        config.errorCallback();
      }
      return Promise.reject(responseData.info);
    } else {
      if (responseData.code == 200) {
        return responseData;
      } else if (responseData.code == 901) {
        setTimeout(() => {
          router.push("/login")
        }, 1500);
        return Promise.reject("登录超时");
      }
    }
  }, (error) => {
    return Promise.reject("网络异常!")
  })

  return instance.post(url, params).catch(error => {
    ElMessage({
      message: error,
      type: 'error'
    })
    return null
  })
}




export default request;